//
//  SLTabBarController.h
//  SLTabBarVc+NavigationVc
//
//  Created by 伟仔c on 15/3/2.
//  Copyright (c) 2015年 SL. All rights reserved.
//

#import "SLTabBar.h"
#import "SLTabBarButton.h"

@interface SLTabBar()

/** 记录选中的按钮 */
@property (nonatomic, weak) SLTabBarButton *selectedButton;
@end


@implementation SLTabBar

#pragma mark -创建一个TabBar按钮
- (void)addTabBarButtonWithImage:(NSString *)image SelectImage:(NSString *)selectImage {
    
    // 1.创建按钮
    SLTabBarButton *btn = [SLTabBarButton buttonWithType:UIButtonTypeCustom];
    
    // 2.设置图片
    [btn setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:selectImage] forState:UIControlStateSelected];
    
    // 3.监听点击
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
    
    // 4.添加到父控件
    [self addSubview:btn];
}

#pragma mark -监听按钮点击
- (void)btnClick:(SLTabBarButton *)button {
    
    // 1.切换高亮状态
    _selectedButton.selected = NO;
    button.selected = YES;
    _selectedButton = button;
    
    // 2.切换选中的控制器
    if ([_delegate respondsToSelector:@selector(tabBar:didSelectIndex:)]) {
        [_delegate tabBar:self didSelectIndex:button.tag];
    }
}

#pragma mark -布局控件位置
- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 1.计算按钮尺寸
    CGFloat btnW = self.bounds.size.width / self.subviews.count;
    CGFloat btnH = self.bounds.size.height;
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    
    // 2.设置按钮位置
    for (int i = 0; i < self.subviews.count; i++) {
        SLTabBarButton *btn = self.subviews[i];
        btnX = i * btnW;
        btn.tag = i;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        // 2.1 默认选中第一个按钮
        if (i == 0) [self btnClick:btn];
    }
}


@end
